#ifndef _LOCK_H_
#define _LOCK_H_
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "osplatform.h"
#ifndef WIN32
#include <sys/types.h>
#include <unistd.h>
#include <pthread.h>
#include <errno.h>
#include <stdlib.h>

#else
#include <windows.h>
#endif
#ifndef WIN32
class CLock
{
public:
	CLock()
	{		
		pthread_mutex_init(&m_hLock,NULL);	
	};
	virtual ~CLock()
	{
		pthread_mutex_destroy(&m_hLock);
	};
	int32 Lock()
	{
		pthread_mutex_lock(&m_hLock);
		return 0;
	};
	bool TryLock()
	{
		return (pthread_mutex_trylock(&m_hLock) !=EBUSY);
	};
	void Unlock()
	{
		pthread_mutex_unlock(&m_hLock);
	};
	void SetName(const int8 *name){strncpy(m_sName,name,15);m_sName[15] = '\0';};
private:
	pthread_mutex_t m_hLock;
	int8	m_sName[16];
};
#else
class CLock 
{
public:
	CLock()
	{
		InitializeCriticalSection(&m_CriticalSection);
	};
	virtual ~CLock()
	{DeleteCriticalSection(&m_CriticalSection);};
	BOOL TryLock()
	{
		return TryEnterCriticalSection(
			&m_CriticalSection  // critical section
			);
	};
	void Lock()
	{EnterCriticalSection(&m_CriticalSection);};
	void Unlock()
	{LeaveCriticalSection(&m_CriticalSection);};
private:
	CRITICAL_SECTION m_CriticalSection;
};
#endif
class CWaitAndSignal
{
public:
	CWaitAndSignal(const CLock &l,BOOL wait=TRUE):lock((CLock &)l)
	{		
		if(wait)		
			lock.Lock();
	}
	~CWaitAndSignal()
	{
		lock.Unlock();
	}
protected:
	CLock &lock;
};

#endif

